
package com.kanjian.music.service;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.kanjian.music.broadcast.NotificationReceiver;
import com.kanjian.music.constants.IntentConstants;
import com.kanjian.music.download.DownloadManager;
import com.kanjian.music.download.MusicDownloadListener;
import com.kanjian.music.download.MusicDownloadTask;
import com.kanjian.music.entity.Music;
import com.kanjian.music.listener.PlayerListener;
import com.kanjian.music.util.NotificationUtil;
import com.kanjian.music.util.PlayerUtil;

/**
 * 音乐播放Service
 * 
 * @author xuyanjun@kanjian.com
 */
public class PlayerService extends Service implements MusicDownloadListener {

    private MediaPlayer mMediaPlayer;

    private ArrayList<PlayerListener> mPlayerListenerList;

    private HeadsetReciver mHeadsetReciver;

    private NotificationReceiver mNotificationReceiver;

    private boolean mIsPaused = true;

    private boolean mIsPassivityPaused = false; // 是否被来电获去电被动暂停

    private Music mPlayingMusic;

    private boolean isStoped;

    private boolean isSeeking;

    private static Handler mHandler;

    @Override
    public void onCreate() {
        super.onCreate();
        TelephonyManager teleManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        teleManager.listen(new TelePhoneListener(), PhoneStateListener.LISTEN_CALL_STATE);
        registerBroadcasts();
        mHandler = new Handler();
        initMediaPlayer();
        MusicDownloadTask.registerMusicDownloadListener(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterBroadcasts();
        MusicDownloadTask.unregisterMusicDownloadListener(this);
    }

    /**
     * 初始化播放器
     */
    private void initMediaPlayer() {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                next(false);
            }
        });
        mMediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                callbackBufferingProgress(percent);
            }
        });
        
        mMediaPlayer.setOnInfoListener(new OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                return false;
            }
        });
        
    }

    /**
     * 注册相关广播 1. 耳机插拔广播
     */
    private void registerBroadcasts() {
        mHeadsetReciver = new HeadsetReciver();
        mNotificationReceiver = new NotificationReceiver();
        registerReceiver(mHeadsetReciver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
        IntentFilter filter = new IntentFilter();
        filter.addAction(IntentConstants.ACTION_NOTIFICATION_ACTION_NEXT);
        filter.addAction(IntentConstants.ACTION_NOTIFICATION_ACTION_PRE);
        filter.addAction(IntentConstants.ACTION_NOTIFICATION_ACTION_PLAY);
        registerReceiver(mNotificationReceiver, filter);
    }

    /**
     * 注销相关广播
     */
    private void unregisterBroadcasts() {
        unregisterReceiver(mHeadsetReciver);
        unregisterReceiver(mNotificationReceiver);
    }

    /**
     * 注册播放器监听器
     * 
     * @param listener
     */
    public void registerPlayerListener(PlayerListener listener) {
        if (mPlayerListenerList == null) {
            mPlayerListenerList = new ArrayList<PlayerListener>();
        }
        if (!mPlayerListenerList.contains(listener)) {
            mPlayerListenerList.add(listener);
        }
        if (isPlaying()) {
            callbackOnPlay();
        }
    }

    /**
     * 注销播放器监听器
     * 
     * @param listener
     */
    public void unregisterPlayerListener(PlayerListener listener) {
        if (mPlayerListenerList != null) {
            mPlayerListenerList.remove(listener);
        }
    }

    /**
     * 通知播放进度更新
     * 
     * @param percent 播放百分比 0-1
     */
    private void callbackPlayProgress(float percent) {
        if (mPlayerListenerList != null) {
            int playTime = 0;
            if (mPlayingMusic.getPlayTime() != null) {
                playTime = (int) (mPlayingMusic.getPlayTime() * percent);
            }
            for (int i = 0; i < mPlayerListenerList.size(); i++) {
                mPlayerListenerList.get(i).onProgress(percent, playTime);
            }
        }
    }

    /**
     * 通知缓冲进度更新
     * 
     * @param percent 缓冲百分比 0-1
     */
    private void callbackBufferingProgress(int percent) {
        if (mPlayerListenerList != null) {
            for (int i = 0; i < mPlayerListenerList.size(); i++) {
                mPlayerListenerList.get(i).onBuffing(percent);
            }
        }
    }

    private void callbackOnPlay() {
        if (mPlayerListenerList != null) {
            for (int i = 0; i < mPlayerListenerList.size(); i++) {
                mPlayerListenerList.get(i).onPlay(mPlayingMusic);
            }
        }
    }

    private void callbackOnPause() {
        if (mPlayerListenerList != null) {
            for (int i = 0; i < mPlayerListenerList.size(); i++) {
                mPlayerListenerList.get(i).onMusicPause();
            }
        }
    }

    private void callbackContinuePlay() {
        if (mPlayerListenerList != null) {
            for (int i = 0; i < mPlayerListenerList.size(); i++) {
                mPlayerListenerList.get(i).onContinuePlay();
            }
        }
    }

    private void calcPlayProgress() {
        if (isSeeking || isStoped) {
            return;
        }
        if (mPlayingMusic != null && mPlayingMusic.getPlayTime() != null) {
            float percent = ((float) mMediaPlayer.getCurrentPosition() / (mPlayingMusic
                    .getPlayTime() * 1000));
            callbackPlayProgress(percent);
            Runnable recursion = new Runnable() {
                public void run() {
                    calcPlayProgress();
                }
            };
            mHandler.postDelayed(recursion, 1000);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return false;
    }

    public void log(String s) {
        Log.e("PlayerService", s);
    }

    // 播放按钮处理
    public void play() {
        // TODO 实现播放
        mPlayingMusic = PlayerUtil.getCurrentPlayingMusic();
        if (mPlayingMusic == null) {
            return;
        }
        try {
            mMediaPlayer.reset();

            // 已下载
            if (mPlayingMusic.isDownloaded()) {
                mMediaPlayer.setDataSource(mPlayingMusic.mLocalPath);
            } else {
                // 边听边存
                if (PlayerUtil.isDownloadOnPlaying()) {
                    MusicDownloadTask task = new MusicDownloadTask(mPlayingMusic, 1, false);
                    DownloadManager.addUrgentTask(task);
                    mTargetBuffingMusic = mPlayingMusic;
                    return;
                } else {
                    mMediaPlayer.setDataSource(mPlayingMusic.getMusicUrl());
                }
            }

            mMediaPlayer.prepareAsync();
            mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                    mIsPaused = false;
                    calcPlayProgress();
                    callbackOnPlay();
                    NotificationUtil.showCurrentPlayingMusic();
                }
            });
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 是否正在播放
    public boolean isPlaying() {
        if (mMediaPlayer != null) {
            return mMediaPlayer.isPlaying();
        }
        return false;
    }

    // 暂停播放
    public void pause() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
            callbackOnPause();
            mIsPaused = true;
        }
    }

    public void togglePlay() {
        if (mMediaPlayer != null && mPlayingMusic != null) {
            if (mMediaPlayer.isPlaying()) {
                pause();
            } else {
                continuePlay();
            }
        } else {
            play();
        }
    }

    // 继续播放
    public void continuePlay() {
        if (mMediaPlayer != null && mIsPaused) {
            mMediaPlayer.start();
            callbackContinuePlay();
            mIsPaused = false;
        }
    }

    // 下一首
    public void next(boolean fromUser) {
        if (fromUser || PlayerUtil.mPlayerType == PlayerUtil.PLAYERTYPE_RADIO) {
            PlayerUtil.next();
        }
        play();
    }

    // 上一首
    public void pre() {
        PlayerUtil.pre();
        play();
    }

    // 停止
    public void release() {
        mMediaPlayer.stop();
        mMediaPlayer.release();
        mMediaPlayer = null;
    }

    /**
     * 跳转
     * 
     * @param percent 百分比
     */
    public void seek(int percent) {
        mMediaPlayer.seekTo((int) (mMediaPlayer.getDuration() * (percent / 100f)));
    }

    public class PlayerServiceBinder extends Binder {

        public PlayerService getService() {
            return PlayerService.this;
        }
    }

    private PlayerServiceBinder mBinder = new PlayerServiceBinder();

    // 监听电话状态
    private class TelePhoneListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {

            super.onCallStateChanged(state, incomingNumber);
            switch (state) {
            // 挂断
                case TelephonyManager.CALL_STATE_IDLE:
                    if (mIsPassivityPaused) {
                        togglePlay();
                    }
                    break;
                // 来电
                case TelephonyManager.CALL_STATE_RINGING:
                    mIsPassivityPaused = true;
                    pause();
                    break;
                // 去电
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    mIsPassivityPaused = true;
                    pause();
                    break;
            }

        }
    }

    class HeadsetReciver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                int state = intent.getIntExtra("state", -1);
                if (state == 0) {
                    // 耳机拔出
                    pause();
                }
            }
        }
    }

    class NotificationReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                String action = intent.getAction();
                if (action != null) {
                    if (action.equalsIgnoreCase(IntentConstants.ACTION_NOTIFICATION_ACTION_PLAY)) {
                        // 暂停播放
                        togglePlay();
                    } else if (action
                            .equalsIgnoreCase(IntentConstants.ACTION_NOTIFICATION_ACTION_PRE)) {
                        // 上一首
                        pre();
                    } else if (action
                            .equalsIgnoreCase(IntentConstants.ACTION_NOTIFICATION_ACTION_NEXT)) {
                        // 下一首
                        next(true);
                    }
                }
            }
        }
    }

    // 目标下载歌曲 用来与callback的music匹配
    private Music mTargetBuffingMusic;

    private boolean isTriggeredPlay;

    @Override
    public void onStartDownload(Music music) {
    }

    @Override
    public void onProgress(Music music, int progress) {
        if (mTargetBuffingMusic != null && music != null) {
            if (music.mDownloadType == 1 && mTargetBuffingMusic.equals(music)) {
                if (!isTriggeredPlay && progress >= 20) {
                    isTriggeredPlay = true;
                    try {
                        mMediaPlayer.setDataSource(music.mLocalPath);
                        mMediaPlayer.start();
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (SecurityException e) {
                        e.printStackTrace();
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    @Override
    public void finishDownload(Music music, int downloadStatus) {
    }

}
